package cn.it.xiaohan.note.dao;

import cn.it.xiaohan.note.po.User;
import cn.it.xiaohan.note.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDao {

    public User queryUserByName(String userName){
        String sql = "select * from tb_user where uname = ?";
        List<Object> param = new ArrayList<>();
        param.add(userName);
        User user = (User) BaseDao.queryRow(sql,param,User.class);
        return user;
    }

    public User queryUserByName02(String userName) {
        User user = null;
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            connection = DBUtil.getConnection();
            String sql = "select * from tb_user where uname = ?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,userName);
            resultSet = preparedStatement.executeQuery();
            if (resultSet.next()){
                user = new User();
                user.setUserId(resultSet.getInt("userId"));
                user.setUname(userName);
                user.setHead(resultSet.getString("head"));
                user.setMood(resultSet.getString("mood"));
                user.setNick(resultSet.getString("nick"));
                user.setUpwd(resultSet.getString("upwd"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(connection,preparedStatement,resultSet);
        }
        return user;
    }


    public User queryUserByNickAndUserId(String nickName, Integer userId) {
        String sql = "select * from tb_user where nick = ? and userId != ?";
        List<Object> params = new ArrayList<>();
        params.add(nickName);
        params.add(userId);
        User user = (User)BaseDao.queryRow(sql,params,User.class);
        return user;
    }

    /**
     * 更新操作
     * @param user
     * @return
     */
    public int updateUser(User user) {
        // 定义sql语句
        String sql = "update tb_user set nick = ? , mood = ? , head = ? where userId = ?";
        // 设置参数
        List<Object> params = new ArrayList<>();
        params.add(user.getNick());
        params.add(user.getMood());
        params.add(user.getHead());
        params.add(user.getUserId());
        // 调用BaseDao的更新方法返回受影响的行数
        int row = BaseDao.executeUpdate(sql,params);
        return row;
    }
}
